<template>
  <el-dialog 
    v-model="visible" 
    :title="dialogTitle"
    width="600px"
    @close="handleClose"
  >
    <div v-if="currentItem">
      <!-- 文件夹权限设置 -->
      <div v-if="currentItem.file_type === 'folder'">
        <h4>文件夹权限设置</h4>
        
        <!-- 部门权限 -->
        <div class="permission-section">
          <h5>部门权限</h5>
          <el-form :model="departmentForm" inline>
            <el-form-item label="部门">
              <el-select v-model="departmentForm.department_id" placeholder="选择部门">
                <el-option 
                  v-for="dept in departments" 
                  :key="dept.id" 
                  :label="dept.name" 
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="权限">
              <el-select v-model="departmentForm.permission" placeholder="选择权限">
                <el-option label="只读" value="read" />
                <el-option label="读写" value="write" />
                <el-option label="管理" value="manage" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addDepartmentPermission">添加</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 已设置的部门权限列表 -->
          <el-table :data="folderPermissions.departments" size="small">
            <el-table-column label="部门" prop="department_name" />
            <el-table-column label="权限">
              <template #default="{ row }">
                <el-tag :type="getPermissionTagType(row.permission)">
                  {{ getPermissionText(row.permission) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeDepartmentPermission(row.department_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 用户权限 -->
        <div class="permission-section">
          <h5>用户权限</h5>
          <el-form :model="userForm" inline>
            <el-form-item label="用户">
              <el-select v-model="userForm.user_id" placeholder="选择用户" filterable>
                <el-option 
                  v-for="user in users" 
                  :key="user.id" 
                  :label="user.username" 
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="权限">
              <el-select v-model="userForm.permission" placeholder="选择权限">
                <el-option label="只读" value="read" />
                <el-option label="读写" value="write" />
                <el-option label="管理" value="manage" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addUserPermission">添加</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 已设置的用户权限列表 -->
          <el-table :data="folderPermissions.users" size="small">
            <el-table-column label="用户" prop="username" />
            <el-table-column label="权限">
              <template #default="{ row }">
                <el-tag :type="getPermissionTagType(row.permission)">
                  {{ getPermissionText(row.permission) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeUserPermission(row.user_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <!-- 文件共享设置 -->
      <div v-else>
        <h4>文件共享设置</h4>
        <el-form :model="shareForm" label-width="100px">
          <el-form-item label="共享级别">
            <el-radio-group v-model="shareForm.share_level">
              <el-radio label="private">私有</el-radio>
              <el-radio label="department">部门内共享</el-radio>
              <el-radio label="public">公开</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="savePermissions" :loading="saving">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'

const props = defineProps({
  modelValue: Boolean,
  item: Object
})

const emit = defineEmits(['update:modelValue', 'saved'])

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const currentItem = ref(null)
const departments = ref([])
const users = ref([])
const saving = ref(false)

const folderPermissions = reactive({
  departments: [],
  users: []
})

const departmentForm = reactive({
  department_id: null,
  permission: 'read'
})

const userForm = reactive({
  user_id: null,
  permission: 'read'
})

const shareForm = reactive({
  share_level: 'private'
})

// 计算属性
const dialogTitle = computed(() => {
  if (!currentItem.value) return ''
  return currentItem.value.file_type === 'folder' 
    ? `文件夹权限设置 - ${currentItem.value.name}`
    : `文件共享设置 - ${currentItem.value.name}`
})

// 监听器
watch(() => props.item, (newItem) => {
  if (newItem) {
    currentItem.value = newItem
    if (newItem.file_type === 'folder') {
      loadFolderPermissions()
    } else {
      loadFileShare()
    }
  }
}, { immediate: true })

watch(visible, (newVisible) => {
  if (newVisible) {
    loadDepartments()
    loadUsers()
  }
})

// 方法
const loadDepartments = async () => {
  try {
    const response = await api.get('/departments/')
    departments.value = response.data
  } catch (error) {
    ElMessage.error('加载部门列表失败')
  }
}

const loadUsers = async () => {
  try {
    const response = await api.get('/users/')
    users.value = response.data
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  }
}

const loadFolderPermissions = async () => {
  if (!currentItem.value) return
  
  try {
    const response = await api.get(`/permissions/folder/${currentItem.value.id}`)
    folderPermissions.departments = response.data.departments || []
    folderPermissions.users = response.data.users || []
  } catch (error) {
    ElMessage.error('加载文件夹权限失败')
  }
}

const loadFileShare = async () => {
  if (!currentItem.value) return
  
  try {
    const response = await api.get(`/permissions/file/${currentItem.value.id}/share`)
    shareForm.share_level = response.data.share_level || 'private'
  } catch (error) {
    ElMessage.error('加载文件共享信息失败')
  }
}

const addDepartmentPermission = async () => {
  if (!departmentForm.department_id || !departmentForm.permission) {
    ElMessage.warning('请选择部门和权限')
    return
  }
  
  try {
    await api.post(`/permissions/folder/${currentItem.value.id}/department`, {
      department_id: departmentForm.department_id,
      permission: departmentForm.permission
    })
    
    ElMessage.success('部门权限添加成功')
    departmentForm.department_id = null
    departmentForm.permission = 'read'
    loadFolderPermissions()
  } catch (error) {
    ElMessage.error('添加部门权限失败')
  }
}

const removeDepartmentPermission = async (departmentId) => {
  try {
    await api.delete(`/permissions/folder/${currentItem.value.id}/department/${departmentId}`)
    ElMessage.success('部门权限删除成功')
    loadFolderPermissions()
  } catch (error) {
    ElMessage.error('删除部门权限失败')
  }
}

const addUserPermission = async () => {
  if (!userForm.user_id || !userForm.permission) {
    ElMessage.warning('请选择用户和权限')
    return
  }
  
  try {
    await api.post(`/permissions/folder/${currentItem.value.id}/user`, {
      user_id: userForm.user_id,
      permission: userForm.permission
    })
    
    ElMessage.success('用户权限添加成功')
    userForm.user_id = null
    userForm.permission = 'read'
    loadFolderPermissions()
  } catch (error) {
    ElMessage.error('添加用户权限失败')
  }
}

const removeUserPermission = async (userId) => {
  try {
    await api.delete(`/permissions/folder/${currentItem.value.id}/user/${userId}`)
    ElMessage.success('用户权限删除成功')
    loadFolderPermissions()
  } catch (error) {
    ElMessage.error('删除用户权限失败')
  }
}

const savePermissions = async () => {
  if (currentItem.value.file_type === 'file') {
    await saveFileShare()
  }
  handleClose()
}

const saveFileShare = async () => {
  saving.value = true
  try {
    await api.put(`/permissions/file/${currentItem.value.id}/share`, {
      share_level: shareForm.share_level
    })
    ElMessage.success('文件共享设置保存成功')
    emit('saved')
  } catch (error) {
    ElMessage.error('保存文件共享设置失败')
  } finally {
    saving.value = false
  }
}

const handleClose = () => {
  visible.value = false
  currentItem.value = null
  folderPermissions.departments = []
  folderPermissions.users = []
  shareForm.share_level = 'private'
}

const getPermissionText = (permission) => {
  const map = {
    read: '只读',
    write: '读写',
    manage: '管理'
  }
  return map[permission] || permission
}

const getPermissionTagType = (permission) => {
  const map = {
    read: 'info',
    write: 'warning',
    manage: 'danger'
  }
  return map[permission] || 'info'
}
</script>

<style scoped>
.permission-section {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.permission-section h5 {
  margin: 0 0 15px 0;
  color: #303133;
}

.el-table {
  margin-top: 15px;
}
</style>